package com.ruoyi.chiwen.controller.api;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.ruoyi.chiwen.domain.ConfigEntity;
import com.ruoyi.chiwen.domain.TbUser;
import com.ruoyi.chiwen.service.ITbUserService;
import com.ruoyi.chiwen.util.TLSSigAPIv2;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.UserTokenService;
import com.ruoyi.framework.web.service.WxLoginUser;
import io.rong.models.User;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.util.*;

/**
 * app 用户接口
 *
 * @author tf
 */
@RestController
@RequestMapping("/chiwen/userapi")
public class UserApiController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private ITbUserService tbUserService;

    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public AjaxResult testLogin(String phone,String token){
        logger.info("前端用户登录");
        TbUser tbUser = new TbUser();
        tbUser.setPhoneNumber(phone);
        List<TbUser> tbUsers = tbUserService.selectTbUserList(tbUser);
        WxLoginUser wxLoginUser =new WxLoginUser();
        Map<String,Object> map = new HashMap<>();
        if(tbUsers == null || tbUsers.size() == 0){
            tbUser.setInfoIsOk(0);
            tbUser.setStepsNumber(Long.valueOf(1));
            tbUser.setRyToken(String.valueOf(0));
            tbUserService.insertTbUser(tbUser);
            tbUsers = tbUserService.selectTbUserList(tbUser);
//            return AjaxResult.error("登录失败，不存在此用户");
        }else if(tbUsers.get(0).getIsDeleted() == 1){
            return AjaxResult.error("该账号已被封禁，请联系管理员");
        }
        wxLoginUser.setUserId(tbUsers.get(0).getUserId());
        wxLoginUser.setPhoneNumer(phone);
        wxLoginUser.setInfoIsOk(tbUsers.get(0).getInfoIsOk());
        wxLoginUser.setStepsNumber(tbUsers.get(0).getStepsNumber());
        wxLoginUser.setRyToken(tbUsers.get(0).getRyToken());
        wxLoginUser.setUserType(tbUsers.get(0).getUserType());

        token = userTokenService.createToken(wxLoginUser);
        map.put("userInfo",wxLoginUser);
        map.put("token",token);
        return AjaxResult.success(map);
    }

    /**
     *  完善用户信息
     * @param tbUser   用户信息
     * @return
     */
    @PostMapping("/update/userInfo")
    public AjaxResult updateUserInfo(@RequestBody TbUser tbUser){
        tbUser.setStepsNumber(4L);
        tbUserService.updateTbUser(tbUser);
        return AjaxResult.success("ok");
    }

    @GetMapping("/testToken")
    public AjaxResult testToken(HttpServletRequest request){
        String token = userTokenService.getToken(request);
        System.out.println("请求的token是"+token);
        return AjaxResult.success(token);
    }

    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request){
        String token = userTokenService.getToken(request);
        WxLoginUser wxLoginUser = userTokenService.getWxLoginUser(token);
        TbUser tbUser = tbUserService.selectTbUserById(wxLoginUser.getUserId());
        return AjaxResult.success(tbUser);
    }

    @GetMapping("/getfaceSign")
    public AjaxResult face(String appid,String nonce,String userid,HttpServletRequest request) throws IOException {
//        String appid = "IDAJg4hO";
        String Secret = "jSiGO1HlfyGXC7DggfA4KRlo7uvuKh6frIc9mXZlflNM8k2OEZo4Vw0g6vliAy2G";
        String urlParam = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id="+appid+"&secret="+Secret+"&grant_type=client_credential&version=1.0.0";
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建GET请求方法实例对象
        GetMethod getMethod = new GetMethod(urlParam);
        // 设置post请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");

        httpClient.executeMethod(getMethod);

        String result = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();

//        System.out.println(result);

        JSONObject jo = JSONObject.parseObject(new String(result));
        String access_token = jo.getString("access_token");
//        System.out.println(access_token);

//        urlParam = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id="+appid+"&access_token="+access_token+"&type=nonceticket&version=1.0.0";
        urlParam = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id="+appid+"&access_token="+access_token+"&type=NONCE&version=1.0.0&user_id="+userid;
        // 创建GET请求方法实例对象
        getMethod = new GetMethod(urlParam);
        // 设置post请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");
        httpClient.executeMethod(getMethod);
        result = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        Map<String, Object> innerMap = JSONObject.parseObject(new String(result)).getInnerMap();
        List<Map<String,Object>> list = (List<Map<String, Object>>) innerMap.get("tickets");
        String ticket = (String) list.get(0).get("value");

//        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa---");
//        System.out.println("appid:"+appid);
//        System.out.println("userid:"+userid);
//        System.out.println("nonce"+nonce);
//        System.out.println("version:"+"1.0.0");
//        System.out.println("ticket:"+ticket);

        List<String> stringList = new ArrayList<>();
        stringList.add(appid);
        stringList.add(userid);
        stringList.add(nonce);
        stringList.add("1.0.0");
        String sign = sign(stringList, ticket);

        return AjaxResult.success(sign);
    }

//获取通话编码
    @GetMapping("/genUserSig")
    public AjaxResult genUserSig(@RequestParam String userId){
        ConfigEntity configEntity = new ConfigEntity();
        TLSSigAPIv2 apIv2 = new TLSSigAPIv2(Long.valueOf(configEntity.getSecretId()), configEntity.getSecretKey());
//        System.out.println(Long.valueOf(configEntity.getSecretId()));
//        System.out.println(configEntity.getSecretKey());
        String userSig = apIv2.genUserSig(userId, 86400);
        return AjaxResult.success(userSig);
    }

//    获取客服信息
    @GetMapping("/getKeFu")
    public AjaxResult getKeFu(){
        TbUser tbUser = new TbUser();
        tbUser.setUserType("1");
        List<TbUser> tbUsers = tbUserService.selectTbUserList(tbUser);
//        有且只有一个客服
        return AjaxResult.success(tbUsers);
    }


    @GetMapping("/getAllUserInfo")
    public AjaxResult getAllUserInfo(){
        TbUser tbUser = new TbUser();
        tbUser.setUserType("0");
        tbUser.setUserStatus(1);
        tbUser.setIsDeleted(0);
        List<TbUser> tbUsers = tbUserService.selectTbUserList(tbUser);
        return AjaxResult.success(tbUsers);
    }



    public static String sign(List<String> values, String ticket) {
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        values.add(ticket);
        java.util.Collections.sort(values);
        StringBuilder sb = new StringBuilder();
        for (String s : values) {
            sb.append(s);
        }
        System.out.println("sb");
        System.out.println(sb);
        return Hashing.sha1().hashString(sb, Charsets.UTF_8).toString().toUpperCase();
    }
}
